package com.example.roomjavademo;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;

import com.example.roomjavademo.entity.UserBean;
import com.example.roomjavademo.view_model.UserViewModel;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TextView mTvDeleteAllUser;
    private TextView mTvAdd;
    private TextView mTvDelete;
    private TextView mTvUpdate;
    private TextView mTvResult;
    private List<UserBean> mList = new ArrayList<>();
    private UserViewModel mUserViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTvDeleteAllUser = findViewById(R.id.tv_delete_all_user);
        mTvAdd = findViewById(R.id.tv_add);
        mTvDelete = findViewById(R.id.tv_delete);
        mTvUpdate = findViewById(R.id.tv_update);
        mTvResult = findViewById(R.id.tv_result);
        mUserViewModel = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(), this)).get(UserViewModel.class);
        mUserViewModel.getListLiveData().observe(this, userBeans -> {
            mList.clear();
            mList.addAll(userBeans);
            mTvResult.setText(getUserResultString(userBeans));
        });
        mTvDeleteAllUser.setOnClickListener(v -> mUserViewModel.deleteAll());
        mTvAdd.setOnClickListener(v -> {
            mUserViewModel.insert(new UserBean());
        });
        mTvDelete.setOnClickListener(v -> {
            if (mList.size() > 0) {
                mUserViewModel.delete(mList.get(mList.size() - 1));
            }
        });
        mTvUpdate.setOnClickListener(v -> {
            if (mList.size() <= 0) return;
            UserBean userBean = mList.get(mList.size() - 1);
            userBean.setLastName("改动的数据");
            mUserViewModel.update(userBean);
        });
    }

    private String getUserResultString(List<UserBean> list) {
        StringBuilder stringBuilder = new StringBuilder();
        for (UserBean userBean : list) {
            if (stringBuilder.length() > 0) {
                stringBuilder.append(",");
            }
            stringBuilder.append(userBean.getUid() + "(" + userBean.getLastName()
                    + "," + userBean.getAge() + "岁" + "," + userBean.getSex() + ")");
        }
        return stringBuilder.toString();
    }
}
